package updownLoad.upload;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.management.StringValueExp;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sun.org.apache.bcel.internal.generic.INSTANCEOF;

import cn.itcast.commons.CommonUtils;

@SuppressWarnings(value = { "all" })
public class UpLoadUtilsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        // D:/apache-tomcat-7.0.42/webapps/updownLoad/upLoadcache
        String upLoadCache = this.getServletContext().getRealPath("/upLoadcache");
        File cacheDir = new File(upLoadCache);
        if (!cacheDir.exists()) //其实可以不用判断直接mkdirs的,此处只为装逼
            cacheDir.mkdirs();
        DiskFileItemFactory factory = new DiskFileItemFactory(500 * 1024, cacheDir); // 上传文件超过20kb就进行缓存
        ServletFileUpload sfu = new ServletFileUpload(factory);
        sfu.setFileSizeMax(1024 * 1024 * 200);                                     // 单个文件不能超过500kb, 超过则抛异常
        sfu.setSizeMax(1024 * 1024 * 1024);                                        // 限制整个表单的大小为100M, 超过就抛异常
        try {
            List<FileItem> itemList = sfu.parseRequest(req);
            for (FileItem fileItem : itemList) {
                // 过滤掉普通表单项
                if (fileItem.getName() != null) {
                    String root = this.getServletContext().getRealPath("/WEB-INF/files/"); // 根据相对路径获取绝对路径
                    String fileName = fileItem.getName();
                    String randomUUID = UUID.randomUUID().toString();
                    String saveFileName = randomUUID + fileName;
                    char firstChar = getOneHashChar(saveFileName, 0);
                    char secondChar = getOneHashChar(saveFileName, 1);
                    File dirFile = new File(root, firstChar + "/" + secondChar);
                    dirFile.mkdirs();
                    File saveFile = new File(dirFile, saveFileName);
                    fileItem.write(saveFile); // FileItem很贴心的提供了保存流的功能,所以不用自己getInput和output了
                    resp.sendRedirect("/updownLoad/result.jsp");
                }
            }
        } catch (FileUploadException e) {
            if (e instanceof FileUploadBase.FileSizeLimitExceededException) {
                req.setAttribute("msg", "上传的文件太大啦");
                req.getRequestDispatcher("/result.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private char getOneHashChar(String string, int num) {
        if (string.length() < num)
            return (Character) null;
        String filehashStr = Integer.toHexString(string.hashCode());
        StringBuilder stringBuilder = new StringBuilder(filehashStr);
        char firstChar = stringBuilder.reverse().toString().charAt(num);
        return firstChar;
    }
}
